package com.haixiaoke.saas.repository.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.haixiaoke.saas.repository.dto.HousingAllocationDTO;
import com.haixiaoke.saas.repository.exception.BizException;
import com.haixiaoke.saas.repository.mapper.HousingAllocationMapper;
import com.haixiaoke.saas.repository.pojo.*;
import com.haixiaoke.saas.repository.service.*;
import com.haixiaoke.saas.repository.util.GsonUtil;
import com.haixiaoke.saas.repository.util.LocationUtils;
import com.haixiaoke.saas.repository.util.PageUtil;
import com.haixiaoke.saas.repository.vo.ApartmentDetailVo;
import com.haixiaoke.saas.repository.vo.HouseConditionVO;
import com.haixiaoke.saas.repository.vo.HousingAllocationVO;
import com.mzj.saas.commons.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 房屋配置Service业务层处理
 *
 * @author qixi
 * @date 2023-04-10
 */
@Service
public class HousingAllocationServiceImpl implements IHousingAllocationService {
    @Autowired
    private HousingAllocationMapper housingAllocationMapper;
    @Autowired
    private IHotAttractionsService iHotAttractionsService;
    @Autowired
    private IBusinessCircleService iBusinessCircleService;
    @Autowired
    private IDecorationService iDecorationService;
    @Autowired
    private IHouseRecordService iHouseRecordService;
    @Autowired
    private IHouseFacilitiesItemService iHouseFacilitiesItemService;
    @Autowired
    private IHouseFacilitiesService iHouseFacilitiesService;
    @Autowired
    private IMetroStationService iMetroStationService;
    @Autowired
    private IMetroLineStationService iMetroLineStationService;
    @Autowired
    private IApartmentService apartmentService;
    @Autowired
    private IApartmentLabelService iApartmentLabelService;
    @Autowired
    private IOrderService orderService;


    @Override
    public HousingAllocation selectHousingAllocationById(Long allocationId) {
        return housingAllocationMapper.selectHousingAllocationByAllocationId(allocationId);
    }

    /**
     * 查询房屋配置
     *
     * @param allocationId 房屋配置主键
     * @return 房屋配置
     */
    @Override
    public HousingAllocation selectHousingAllocationByAllocationId(Long allocationId) {
        HousingAllocation allocation = housingAllocationMapper.selectHousingAllocationByAllocationId(allocationId);
        if (ObjectUtil.isEmpty(allocation)) {
            return allocation;
        }

        String houseId = allocation.getHouseId();
        List<HouseFacilitiesItem> houseFacilitiesItems = iHouseFacilitiesItemService.selectHouseFacilitiesItemByHouseId(houseId);
        if (!houseFacilitiesItems.isEmpty()) {
            allocation.setFacilitiesItems(houseFacilitiesItems);
        }
        // 景区id处理
        String attractionsIds = allocation.getAttractionsIds();
        if (StrUtil.isNotBlank(attractionsIds)) {
            List<String> split = StrUtil.split(attractionsIds, ',');
            allocation.setAttractionsIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 商区id
        String businessCircleIds = allocation.getBusinessCircleIds();
        if (StrUtil.isNotBlank(businessCircleIds)) {
            List<String> split = StrUtil.split(businessCircleIds, ',');
            allocation.setBusinessCircleIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 房屋设施id
        String facilitiesIds = allocation.getFacilitiesIds();
        if (StrUtil.isNotBlank(facilitiesIds)) {
            List<String> split = StrUtil.split(facilitiesIds, ',');
            allocation.setFacilitiesIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 地铁设施
        String stationIds = allocation.getStationIds();
        if (StrUtil.isNotBlank(stationIds)) {
            List<String> split = StrUtil.split(stationIds, ',');
            allocation.setStationIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }

        Integer apartmentType = allocation.getApartmentType();
        if (HousingAllocation.APARTMENT_TYPE_SHORT == apartmentType) {
            Integer chargeType = allocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                String agingPrice = allocation.getAgingPrice();
                Map<Integer, Double> agingPriceMap = GsonUtil.toMapInteger(agingPrice);
                allocation.setAgingPriceMap(agingPriceMap);
            }
        }
        return allocation;
    }

    /**
     * 查询房屋配置列表
     *
     * @param housingAllocation 房屋配置
     * @return 房屋配置
     */
    @Override
    public List<HousingAllocation> selectHousingAllocationList(HousingAllocation housingAllocation) {

        List<HousingAllocation> housingAllocations = housingAllocationMapper.selectHousingAllocationList(housingAllocation);
        for (HousingAllocation allocation : housingAllocations) {

            String houseId = allocation.getHouseId();
            List<HouseFacilitiesItem> houseFacilitiesItems = iHouseFacilitiesItemService.selectHouseFacilitiesItemByHouseId(houseId);
            if (!houseFacilitiesItems.isEmpty()) {
                allocation.setFacilitiesItems(houseFacilitiesItems);
            }

            // 景区id处理
            String attractionsIds = allocation.getAttractionsIds();
            if (StrUtil.isNotBlank(attractionsIds)) {
                List<String> split = StrUtil.split(attractionsIds, ',');
                allocation.setAttractionsIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            }
            // 商区id
            String businessCircleIds = allocation.getBusinessCircleIds();
            if (StrUtil.isNotBlank(businessCircleIds)) {
                List<String> split = StrUtil.split(businessCircleIds, ',');
                allocation.setBusinessCircleIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            }
            // 房屋设施id
            String facilitiesIds = allocation.getFacilitiesIds();
            if (StrUtil.isNotBlank(facilitiesIds)) {
                List<String> split = StrUtil.split(facilitiesIds, ',');
                allocation.setFacilitiesIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            }

            // 地铁设施
            String stationIds = allocation.getStationIds();
            if (StrUtil.isNotBlank(stationIds)) {
                List<String> split = StrUtil.split(stationIds, ',');
                allocation.setStationIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            }

            // 房屋标签
            String labelIds = allocation.getLabelIds();
            if (StrUtil.isNotBlank(labelIds)) {
                List<String> split = StrUtil.split(labelIds, ',');
                allocation.setStationIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            }

            Integer chargeType = allocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                String agingPrice = allocation.getAgingPrice();
                Map<Integer, Double> agingPriceMap = GsonUtil.toMapInteger(agingPrice);
                allocation.setAgingPriceMap(agingPriceMap);
            }
        }
        return housingAllocations;
    }

    /**
     * 新增房屋配置
     *
     * @param housingAllocation 房屋配置
     * @return 结果
     */
    @Override
    @Transactional
    public int insertHousingAllocation(HousingAllocation housingAllocation) {
        housingAllocation.setCreateTime(new Date());
        String houseId = housingAllocation.getHouseId();

        // 房屋设施价格状态关联表
        List<HouseFacilitiesItem> facilitiesItems = housingAllocation.getFacilitiesItems();
        if (CollectionUtil.isNotEmpty(facilitiesItems)) {
            iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(houseId);
            for (HouseFacilitiesItem facilitiesItem : facilitiesItems) {
                Long facilitiesId = facilitiesItem.getFacilitiesId();
                HouseFacilities facilities = iHouseFacilitiesService.selectHouseFacilitiesByFacilitiesId(facilitiesId);
                if (ObjectUtil.isEmpty(facilities)) {
                    throw new BizException("房屋设施不存在");
                }
                facilitiesItem.setHouseId(houseId);
                facilitiesItem.setFacilitiesName(facilities.getFacilitiesName());
            }
            int count = iHouseFacilitiesItemService.insertHouseFacilitiesItemList(facilitiesItems);
            if (facilitiesItems.size() != count) {
                throw new BizException("房屋设施价格状态新增有误！");
            }
        }


        List<Long> businessCircleIds = housingAllocation.getBusinessCircleIdList();
        // 商区全名
        if (CollectionUtil.isNotEmpty(businessCircleIds)) {
            housingAllocation.setBusinessCircleNames(iBusinessCircleService.selectBusinessCircleFullNamesByIdIn(businessCircleIds));
            housingAllocation.setBusinessCircleIds(StringUtils.join(businessCircleIds, ","));
        }

        List<Long> attractionsIds = housingAllocation.getAttractionsIdList();
        // 热门景点全名
        if (CollectionUtil.isNotEmpty(attractionsIds)) {
            housingAllocation.setAttractionsFullNames(iHotAttractionsService.selectHotAttractionFullNamesByIdIn(attractionsIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }


        List<Long> stationIds = housingAllocation.getStationIdList();
        // 地铁站台
        if (CollectionUtil.isNotEmpty(stationIds)) {
            housingAllocation.setStationNames(iMetroStationService.selectMetroStationNamesByStationIdIn(stationIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }

        List<Long> labelIds = housingAllocation.getLabelIdList();
        // 房屋标签
        if (CollectionUtil.isNotEmpty(labelIds)) {
            housingAllocation.setLabelNames(iApartmentLabelService.selectApartmentLabelNamesByLabelIdIn(labelIds));
            housingAllocation.setLabelIds(StringUtils.join(labelIds, ","));
        }

        Integer apartmentType = housingAllocation.getApartmentType();
        if (HousingAllocation.APARTMENT_TYPE_SHORT == apartmentType) {
            Integer chargeType = housingAllocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_IMMOBILIZATION == chargeType) {
                housingAllocation.setAverageDaily(housingAllocation.getFixedPrice());
            } else if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                Map<Integer, Double> agingPriceMap = housingAllocation.getAgingPriceMap();

                // 获取日均最低价
                String json = JSONUtil.toJsonStr(agingPriceMap);
                housingAllocation.setAgingPrice(json);

                Collection<Double> prices = agingPriceMap.values();
                Object[] array = prices.toArray();
                Arrays.sort(array);
                housingAllocation.setAverageDaily((Double) array[0]);
            }
        }
        // 装修情况
        Decoration decoration = iDecorationService.selectDecorationByDecorationId(housingAllocation.getDecorationId());
        housingAllocation.setDecorationName(decoration.getDecorationName());

        return housingAllocationMapper.insertHousingAllocation(housingAllocation);
    }

    /**
     * 修改房屋配置
     *
     * @param housingAllocation 房屋配置
     * @return 结果
     */
    @Override
    public int updateHousingAllocation(HousingAllocation housingAllocation) {
        housingAllocation.setUpdateTime(new Date());

        Date rentableStartTime = housingAllocation.getRentableStartTime();
        Date rentableEndTime = housingAllocation.getRentableEndTime();
        if (rentableStartTime.getTime() > rentableEndTime.getTime()){
            throw new BizException("开始时间要小于结束时间");
        }

        // 房屋设施价格状态关联表
        List<HouseFacilitiesItem> facilitiesItems = housingAllocation.getFacilitiesItems();
        if (CollectionUtil.isNotEmpty(facilitiesItems)) {
            String houseId = housingAllocation.getHouseId();
            iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(houseId);
            for (HouseFacilitiesItem facilitiesItem : facilitiesItems) {
                Long facilitiesId = facilitiesItem.getFacilitiesId();
                HouseFacilities facilities = iHouseFacilitiesService.selectHouseFacilitiesByFacilitiesId(facilitiesId);
                if (ObjectUtil.isEmpty(facilities)) {
                    throw new BizException("房屋设施不存在");
                }
                facilitiesItem.setHouseId(houseId);
                facilitiesItem.setFacilitiesName(facilities.getFacilitiesName());
            }
            int count = iHouseFacilitiesItemService.insertHouseFacilitiesItemList(facilitiesItems);
            if (facilitiesItems.size() != count) {
                throw new BizException("房屋设施价格状态新增有误！");
            }
        }

        // 商区全名
        List<Long> businessCircleIds = housingAllocation.getBusinessCircleIdList();
        if (CollectionUtil.isNotEmpty(businessCircleIds)) {
            housingAllocation.setBusinessCircleNames(iBusinessCircleService.selectBusinessCircleFullNamesByIdIn(businessCircleIds));
            housingAllocation.setBusinessCircleIds(StringUtils.join(businessCircleIds, ","));
        }else {
            housingAllocation.setBusinessCircleNames(null);
            housingAllocation.setBusinessCircleIds(null);
        }

        // 热门景点全名
        List<Long> attractionsIds = housingAllocation.getAttractionsIdList();
        if (CollectionUtil.isNotEmpty(attractionsIds)) {
            housingAllocation.setAttractionsFullNames(iHotAttractionsService.selectHotAttractionFullNamesByIdIn(attractionsIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }else {
            housingAllocation.setAttractionsFullNames(null);
            housingAllocation.setAttractionsIds(null);
        }

        List<Long> stationIds = housingAllocation.getStationIdList();
        // 地铁站台
        if (CollectionUtil.isNotEmpty(stationIds)) {
            housingAllocation.setStationNames(iMetroStationService.selectMetroStationNamesByStationIdIn(stationIds));
            housingAllocation.setStationIds(StringUtils.join(stationIds, ","));
        }else {
            housingAllocation.setStationNames(null);
            housingAllocation.setStationIds(null);
        }

        List<Long> labelIds = housingAllocation.getLabelIdList();
        // 房屋标签
        if (CollectionUtil.isNotEmpty(labelIds)) {
            housingAllocation.setLabelNames(iApartmentLabelService.selectApartmentLabelNamesByLabelIdIn(labelIds));
            housingAllocation.setLabelIds(StringUtils.join(labelIds, ","));
        }else {
            housingAllocation.setLabelNames(null);
            housingAllocation.setLabelIds(null);
        }

        Integer apartmentType = housingAllocation.getApartmentType();
        if (HousingAllocation.APARTMENT_TYPE_SHORT == apartmentType) {
            Integer chargeType = housingAllocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_IMMOBILIZATION == chargeType) {
                housingAllocation.setAverageDaily(housingAllocation.getFixedPrice());
            } else if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                Map<Integer, Double> agingPriceMap = housingAllocation.getAgingPriceMap();

                String json = JSONUtil.toJsonStr(agingPriceMap);
                housingAllocation.setAgingPrice(json);

                // 计算日均最低价
                Collection<Double> prices = agingPriceMap.values();
                Object[] array = prices.toArray();
                Arrays.sort(array);
                housingAllocation.setAverageDaily((Double) array[0]);
            }
        }


        // 装修情况
        Decoration decoration = iDecorationService.selectDecorationByDecorationId(housingAllocation.getDecorationId());
        housingAllocation.setDecorationName(decoration.getDecorationName());


        return housingAllocationMapper.updateHousingAllocation(housingAllocation);
    }

    /**
     * 批量删除房屋配置
     *
     * @param allocationIds 需要删除的房屋配置主键
     * @return 结果
     */
    @Override
    public int deleteHousingAllocationByAllocationIds(Long[] allocationIds) {
        for (Long allocationId : allocationIds) {
            HousingAllocation housingAllocation = housingAllocationMapper.selectHousingAllocationByAllocationId(allocationId);
            String houseId = housingAllocation.getHouseId();
            iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(houseId);
        }
        return housingAllocationMapper.deleteHousingAllocationByAllocationIds(allocationIds);
    }

    /**
     * 删除房屋配置信息
     *
     * @param allocationId 房屋配置主键
     * @return 结果
     */
    @Override
    public int deleteHousingAllocationByAllocationId(Long allocationId) {
        HousingAllocation housingAllocation = housingAllocationMapper.selectHousingAllocationByAllocationId(allocationId);
        String houseId = housingAllocation.getHouseId();
        iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(houseId);
        return housingAllocationMapper.deleteHousingAllocationByAllocationId(allocationId);
    }

    @Override
    @Transactional
    public int updateHousingAllocationState(HousingAllocation housingAllocation) {
        housingAllocation.setUpdateTime(new Date());
        int count = housingAllocationMapper.updateHousingAllocationState((housingAllocation));
        // 记录房屋状态变更信息
        HouseRecord record = new HouseRecord();
        record.setHouseId(housingAllocation.getHouseId());  // 房屋id
        record.setOperatingTime(housingAllocation.getUpdateTime());    // 操作时间
        record.setOperatingBy(housingAllocation.getUpdateBy());     // 操作人id
        record.setOperatingState(housingAllocation.getApartmentState());    // 操作后的变更状态
        iHouseRecordService.insertHouseRecord(record);
        return count;
    }

    @Override
    public HousingAllocation selectHousingAllocationByHouseId(String houseId) {
        HousingAllocation allocation = housingAllocationMapper.selectHousingAllocationByHouseId(houseId);
        if (ObjectUtil.isEmpty(allocation)) {
            return allocation;
        }

        List<HouseFacilitiesItem> houseFacilitiesItems = iHouseFacilitiesItemService.selectHouseFacilitiesItemByHouseId(houseId);
        if (!houseFacilitiesItems.isEmpty()) {
            allocation.setFacilitiesItems(houseFacilitiesItems);
        }
        // 景区id处理
        String attractionsIds = allocation.getAttractionsIds();
        if (StrUtil.isNotBlank(attractionsIds)) {
            List<String> split = StrUtil.split(attractionsIds, ',');
            allocation.setAttractionsIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 商区id
        String businessCircleIds = allocation.getBusinessCircleIds();
        if (StrUtil.isNotBlank(businessCircleIds)) {
            List<String> split = StrUtil.split(businessCircleIds, ',');
            allocation.setBusinessCircleIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 房屋设施id
        String facilitiesIds = allocation.getFacilitiesIds();
        if (StrUtil.isNotBlank(facilitiesIds)) {
            List<String> split = StrUtil.split(facilitiesIds, ',');
            allocation.setFacilitiesIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }

        String labelIds = allocation.getLabelIds();
        // 房屋标签
        if (StrUtil.isNotBlank(labelIds)) {
            List<String> split = StrUtil.split(labelIds, ',');
            allocation.setLabelIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }


        Integer apartmentType = allocation.getApartmentType();
        if (HousingAllocation.APARTMENT_TYPE_SHORT == apartmentType) {
            Integer chargeType = allocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                String agingPrice = allocation.getAgingPrice();
                // 获取日均最低价
                Map<Integer, Double> agingPriceMap = GsonUtil.toMapInteger(agingPrice);
                allocation.setAgingPriceMap(agingPriceMap);
            }
        }
        return allocation;
    }

    @Override
    public boolean checkHouseIdUnique(String houseId) {
        return housingAllocationMapper.checkHouseIdUnique(houseId) == 0;
    }

    @Override
    public List<HousingAllocationVO> selectHousingAllocationChooseHouse(HousingAllocationDTO dto) {

        Long metroLineId = dto.getMetroLineId();
        // 判断是否传入地铁站点筛选 未传则按照线路进行筛选
        if (ObjectUtil.isNotNull(metroLineId)) {
            List<Long> metroStationIds = dto.getMetroStationIds();
            if (metroStationIds.isEmpty()) {
                List<MetroLineStation> metroLineStations = iMetroLineStationService.selectMetroLineStationByMetroLineId(metroLineId);
                metroStationIds = metroLineStations.stream().map(MetroLineStation::getStationId).distinct().collect(Collectors.toList());
                dto.setMetroStationIds(metroStationIds);
            }
        }

        // 计算距离
        List<HousingAllocationVO> housingAllocationVOS = housingAllocationMapper.selectHousingAllocationChooseHouse(dto);
        for (HousingAllocationVO vo : housingAllocationVOS) {
            if (ObjectUtil.isNotNull(vo.getCommunityLatitude()) && ObjectUtil.isNotNull(vo.getCommunityLongitude())) {
                double distance = LocationUtils.getDistance(vo.getCommunityLatitude(), vo.getCommunityLongitude(),
                        dto.getNowLatitude(), dto.getNowLongitude());
                vo.setDistance((double) Math.round(distance));
            }
        }


        Integer sortType = dto.getSortType();
        if (sortType != null && sortType == 3) {
            housingAllocationVOS = housingAllocationVOS.stream().sorted(Comparator.comparing(HousingAllocationVO::getDistance)).collect(Collectors.toList());
        }else if (sortType == null){
            housingAllocationVOS = housingAllocationVOS.stream().sorted(Comparator.comparing(HousingAllocationVO::getRentStartingTime)).collect(Collectors.toList());
        }

        List<HousingAllocationVO> vos = PageUtil.setPage(housingAllocationVOS);
        for (HousingAllocationVO vo : vos) {
            String houseId = vo.getHouseId();
            if (StrUtil.isNotBlank(houseId)) {
                ApartmentDetailVo detail = apartmentService.getDetail(houseId);
                HousingAllocation allocation = detail.getHousingAllocation();
                if (ObjectUtil.isNotNull(allocation)) {
                    vo.setAddress(allocation.getAddress());
                    vo.setCommunityName(allocation.getCommunityName());
                    vo.setHouseType(allocation.getHouseType());
                    vo.setTitle(allocation.getTitle());
                    vo.setArea(allocation.getArea());
                    vo.setFloor(allocation.getFloor());
                    vo.setTotalFloor(allocation.getTotalFloor());
                }
            }
        }
        return vos;
    }

    @Override
    public List<HousingAllocation> selectByAllocationIds(List<Long> allocationIds) {
        return housingAllocationMapper.selectAllocationIds(allocationIds);
    }

    @Override
    @Transactional
    public int updateHousingAllocationApartmentState(HousingAllocation housingAllocation) {
        List<String> houseIds = housingAllocation.getHouseIds();
        Integer errorCode = Convert.toInt(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (CollectionUtil.isEmpty(houseIds)) {
            throw new BizException(errorCode, "房屋id不得为空");
        }

        // 批量更新上下架状态
        int count = 0;
        List<HousingAllocation> housingAllocations = housingAllocationMapper.selectHousingAllocationByHouseIdIn(houseIds);
        for (HousingAllocation allocation : housingAllocations) {
            allocation.setUpdateTime(new Date());
            allocation.setUpdateBy(housingAllocation.getUpdateBy());
            allocation.setApartmentState(housingAllocation.getApartmentState());
            count += housingAllocationMapper.updateHousingAllocationState((allocation));
            // 记录房屋状态变更信息
            HouseRecord record = new HouseRecord();
            record.setHouseId(housingAllocation.getHouseId());  // 房屋id
            record.setOperatingTime(housingAllocation.getUpdateTime());    // 操作时间
            record.setOperatingBy(housingAllocation.getUpdateBy());     // 操作人id
            record.setOperatingState(housingAllocation.getApartmentState());    // 操作后的变更状态
            iHouseRecordService.insertHouseRecord(record);
        }
        if (houseIds.size() != count) {
            throw new BizException(errorCode, "请配置房源信息");
        }
        return count;
    }

    @Override
    @Transactional
    public int insertHousingAllocationList(HousingAllocation housingAllocation) {
        housingAllocation.setCreateTime(new Date());
        List<String> houseIds = housingAllocation.getHouseIds();
        Integer errorCode = Convert.toInt(StatusCode.ERROR_CODE_40001.getErrorCode());
        if (CollectionUtil.isEmpty(houseIds)) {
            throw new BizException(errorCode, "房屋id不得为空");
        }

        List<Long> businessCircleIds = housingAllocation.getBusinessCircleIdList();
        // 商区全名
        if (CollectionUtil.isNotEmpty(businessCircleIds)) {
            housingAllocation.setBusinessCircleNames(iBusinessCircleService.selectBusinessCircleFullNamesByIdIn(businessCircleIds));
            housingAllocation.setBusinessCircleIds(StringUtils.join(businessCircleIds, ","));
        }

        List<Long> attractionsIds = housingAllocation.getAttractionsIdList();
        // 热门景点全名
        if (CollectionUtil.isNotEmpty(attractionsIds)) {
            housingAllocation.setAttractionsFullNames(iHotAttractionsService.selectHotAttractionFullNamesByIdIn(attractionsIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }


        List<Long> stationIds = housingAllocation.getStationIdList();
        // 地铁站台
        if (CollectionUtil.isNotEmpty(stationIds)) {
            housingAllocation.setStationNames(iMetroStationService.selectMetroStationNamesByStationIdIn(stationIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }

        List<Long> labelIds = housingAllocation.getLabelIdList();
        // 房屋标签
        if (CollectionUtil.isNotEmpty(labelIds)) {
            housingAllocation.setLabelNames(iApartmentLabelService.selectApartmentLabelNamesByLabelIdIn(labelIds));
            housingAllocation.setLabelIds(StringUtils.join(labelIds, ","));
        }


        Integer apartmentType = housingAllocation.getApartmentType();
        if (HousingAllocation.APARTMENT_TYPE_SHORT == apartmentType) {
            Integer chargeType = housingAllocation.getChargeType();
            if (HousingAllocation.CHARGE_TYPE_IMMOBILIZATION == chargeType) {
                housingAllocation.setAverageDaily(housingAllocation.getFixedPrice());
            } else if (HousingAllocation.CHARGE_TYPE_UN_IMMOBILIZATION == chargeType) {
                Map<Integer, Double> agingPriceMap = housingAllocation.getAgingPriceMap();

                // 获取日均最低价
                String json = JSONUtil.toJsonStr(agingPriceMap);
                housingAllocation.setAgingPrice(json);

                Collection<Double> prices = agingPriceMap.values();
                Object[] array = prices.toArray();
                Arrays.sort(array);
                housingAllocation.setAverageDaily((Double) array[0]);
            }
        }
        // 装修情况
        Decoration decoration = iDecorationService.selectDecorationByDecorationId(housingAllocation.getDecorationId());
        housingAllocation.setDecorationName(decoration.getDecorationName());

        housingAllocationMapper.deleteHousingAllocationByHouseIdIn(houseIds);
        int countHousingAllocation = 0;
        for (String houseId : houseIds) {
            housingAllocation.setAllocationId(null);
            housingAllocation.setHouseId(houseId);

            // 房屋设施价格状态关联表
            List<HouseFacilitiesItem> facilitiesItems = housingAllocation.getFacilitiesItems();
            if (CollectionUtil.isNotEmpty(facilitiesItems)) {
                iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(houseId);
                for (HouseFacilitiesItem facilitiesItem : facilitiesItems) {
                    Long facilitiesId = facilitiesItem.getFacilitiesId();
                    HouseFacilities facilities = iHouseFacilitiesService.selectHouseFacilitiesByFacilitiesId(facilitiesId);
                    if (ObjectUtil.isEmpty(facilities)) {
                        throw new BizException("房屋设施不存在");
                    }
                    facilitiesItem.setHouseId(houseId);
                    facilitiesItem.setFacilitiesName(facilities.getFacilitiesName());
                }
                int count = iHouseFacilitiesItemService.insertHouseFacilitiesItemList(facilitiesItems);
                if (facilitiesItems.size() != count) {
                    throw new BizException("房屋设施价格状态新增有误！");
                }
            }
            countHousingAllocation += housingAllocationMapper.insertHousingAllocation(housingAllocation);
        }

        if (houseIds.size() != countHousingAllocation) {
            throw new BizException(errorCode, "房屋批量新增异常");
        }
        return countHousingAllocation;
    }

    @Override
    public int updateAllocation(HousingAllocation allocation) {
        return housingAllocationMapper.updateHousingAllocation(allocation);
    }

    @Override
    public int updateApartmentAllocation(HousingAllocation allocation) {
        return housingAllocationMapper.updateApartmentAllocation(allocation);
    }

    @Override
    public int updateHousingAllocationCleaningType(HousingAllocation housingAllocation) {
        HousingAllocation allocation = housingAllocationMapper.selectHousingAllocationByHouseId(housingAllocation.getHouseId());
        if (ObjectUtil.isNotNull(allocation) && HousingAllocation.CLEANING_TYPE_NO.equals(allocation.getCleaningType())) {
            allocation.setUpdateTime(new Date());
            allocation.setUpdateBy(housingAllocation.getUpdateBy());
            allocation.setCleaningType(HousingAllocation.CLEANING_TYPE_YES);
            housingAllocationMapper.updateHousingAllocationCleaningType(allocation);
            return 1;
        }
        return 0;
    }

    @Override
    public boolean checkLongApartmentTime(Date rentableStartTime, Date rentableEndTime) {
        long day = DateUtil.between(rentableStartTime, rentableEndTime, DateUnit.DAY);
        return day >= 90;
    }

    @Override
    public List<HousingAllocationVO> conditionList(HousingAllocationDTO dto) {
        List<HousingAllocationVO> vos = housingAllocationMapper.conditionList(dto);
        Order order = new Order();
        order.setCheckInTime(dto.getStartTime());
        order.setCheckOutTime(dto.getEndTime());
        for (HousingAllocationVO vo : vos) {
            vo.setTitle(vo.getECommunityName() + vo.getBuildName() + "栋" + vo.getUnitName() + "单元" + vo.getRoomNumber());
            order.setHouseId(vo.getHouseId());
            List<HouseConditionVO> conditionVOs = orderService.selectOrderCondition(order);
            vo.setHouseConditionVOList(conditionVOs);
        }
        return vos;
    }
}
